﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace HtmlCaches
{
    public class ForcedUpdateHandler
    {
        private string cachespath;
        public ForcedUpdateHandler()
        {

        }
        /// <summary>
        /// 强制更新缓存方法：返回值0－未带参数dir，无操作；1－删除主页缓存，11－删除主页失败；2－删除全部缓存，22失败；3－删除对应文件夹，33－失败
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string rootpath = context.Server.MapPath("/");                                                          //获取根目录的物理地址
            cachespath = Path.Combine(rootpath, "caches");                                                   //根目录下caches目录地址
            string dirflag = context.Request.QueryString["dir"];                                                    //传入要删除的目录参数
            string flagid = context.Request.QueryString["id"];                                                       //可能传入ID参数删除对应的具体的那个文章或列表
            string act = context.Request.QueryString["act"] ?? "noact";                                             //传入rootlist参数用来获取htmlcaches.config中的过滤目录


            switch (act.ToLower())
            {
                case "getrootlist": return GetRootList();
                case "delcaches": return Delcaches(dirflag);
                default: return "noact";

            }


        }

        /// <summary>
        /// 删除缓存方法
        /// </summary>
        /// <param name="dir">目录</param>
        /// <returns></returns>
        private string Delcaches(string dir)
        {
            switch (dir.ToLower())
            {
                case "index": return DelIndex(cachespath);
                case "allcaches": return DelDir(cachespath);
                default: return DelDir(cachespath, dir);
            }

        }


        /// <summary>
        /// 获取过滤的目录
        /// </summary>
        /// <returns></returns>
        private string GetRootList()
        {
            string updatetimediff = string.Empty;                                                                       //自动更新时间
            string htmlcache = string.Empty;                                                                            //caches开关锁 仅为open时才有效
            string saverootpath = string.Empty;                                                                         //保存的代码根目录
            string filterpage = string.Empty;                                                                           //过滤哪些页才做处理
            string listpage = string.Empty;
            StringMd5.GetParameters(out updatetimediff, out htmlcache, out saverootpath, out filterpage, out listpage);
            return filterpage;

        }

        /// <summary>
        /// 根据提供的物理路径删除此目录下的所有内容
        /// </summary>
        /// <param name="path">物理路径目录</param>
        private string DelDir(string path)
        {
            if (Directory.Exists(path))
            {
                foreach (var item in Directory.GetDirectories(path))
                {
                    Directory.Delete(item, true);
                }
                foreach (var item in Directory.GetFiles(path))
                {
                    File.Delete(item);
                }
                return "true";
            }
            else
            {
                return "false";
            }
        }



        /// <summary>
        /// 根据提供的物理路径删除此路径下对应的目录文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="dir">要删的目录</param>
        private string DelDir(string path, string dir)
        {
            string flag = "false";
            if (Directory.Exists(path))
            {
                foreach (var item in Directory.GetDirectories(path))
                {

                    if (item.ToLower().Contains(dir.ToLower()))
                    {
                        Directory.Delete(item, true);
                        flag = "true";
                        break;
                    }

                }

            }
            return flag;

        }

        /// <summary>
        /// 删除主页缓存
        /// </summary>
        /// <param name="path"></param>
        private string DelIndex(string path)
        {
            string flag = "false";
            foreach (var item in Directory.GetFiles(path))
            {
                File.Delete(item);
                flag = "true";
            }
            return flag;
        }

        /// <summary>
        /// 获取某个目录下对应的某体的某个文件
        /// </summary>
        /// <param name="path">目录</param>
        /// <param name="dir">文件侠</param>
        /// <param name="filename">文件名，对应的是传入的ＩＤ</param>
        /// <returns></returns>
        private bool DelFileFromDir(string path, string dir, string filename)
        {
            bool flag = false;
            string detailpath = Path.Combine(path, dir);
            if (Directory.Exists(detailpath))
            {
                foreach (var item in Directory.GetFiles(detailpath))
                {
                    if (item.ToLower().Contains(filename))
                    {
                        File.Delete(item);
                        flag = true;

                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据提供的物理路径保存每次强制更新的内容
        /// </summary>
        /// <param name="path">物理路径目录</param>
        private void WriteRecord(string path, string dir, string isdel)
        {
            string updaterecordpath = Path.Combine(path, "updaterecord.txt");
            string updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string inputstr = "upsettime_" + updatetime + "   deldir__ " + dir + "  " + isdel + "\r\n";

            StreamWriter sw = new StreamWriter(updaterecordpath, true, System.Text.Encoding.UTF8);
            sw.Write(inputstr);
            sw.Close();

        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
